<template>
  <div class="container">
    <a-space direction="vertical" :size="16" style="display: block">
      <a-row style="margin-bottom: 16px" :gutter="16">
        <a-col :span="4">
          <a-list style="background-color: white">
            <a-list-item
              v-for="item in weixinStore.wxList"
              :key="item.wxid"
              @click="handle(item)"
              :style="{
                backgroundColor:
                  currentWxid === item.wxid ? '#FFFCE8' : 'white',
              }"
            >
              <a-list-item-meta :title="item.nick" :description="item.wxNum">
                <template #avatar>
                  <a-avatar>
                    <img alt="avatar" :src="item.avatarUrl" />
                  </a-avatar>
                </template>
              </a-list-item-meta>
              <template #actions>
                <icon-caret-right
                  :style="{ color: currentWxid === item.wxid ? '#F53F3F' : '' }"
                />
              </template>
            </a-list-item>
          </a-list>
        </a-col>
        <a-col :span="20">
          <a-card :loading="loading">
            <a-space>
              <a-avatar :size="24" shape="square">
                <img alt="avatar" :src="currentAvatar" />
              </a-avatar>
              <div>自动同意好友请求开关</div>
              <a-switch
                v-model="isautoPass"
                type="round"
                @change="(value) => handleAutoAcceptChange(Boolean(value))"
                :disabled="!currentWxid"
              >
                <template #checked>ON</template>
                <template #unchecked>OFF</template>
              </a-switch>
              <a-button ref="friendListRef" @click="handleUpdateFriend()">
                同步好友数据
              </a-button>
              <a-button ref="groupListRef" @click="handleUpdateGroup()">
                同步群聊数据
              </a-button>
            </a-space>
            <a-divider />
            <a-tabs v-model:active-key="activeTab" :position="position" @tab-click="handleTabClick">
              <a-tab-pane key="1">
                <template #title>
                  <a-avatar :size="24" shape="square">
                    <img alt="avatar" :src="currentAvatar" />
                  </a-avatar>
                  好友
                </template>
                <FriendList :wxid="currentWxid" v-if="loadedTabs['1']" />
              </a-tab-pane>
              <a-tab-pane key="2">
                <template #title>
                  <a-avatar :size="24" shape="square">
                    <img alt="avatar" :src="currentAvatar" />
                  </a-avatar>
                  群聊
                </template>
                <GroupList :wxid="currentWxid" v-if="loadedTabs['2']" />
              </a-tab-pane>
              <a-tab-pane key="4">
                <template #title>
                  <a-avatar :size="24" shape="square">
                    <img alt="avatar" :src="currentAvatar" />
                  </a-avatar>
                  手机加好友
                </template>
                <FriendAdd :wxid="currentWxid" v-if="loadedTabs['4']" />
              </a-tab-pane>
              <!-- <a-tab-pane key="5">
                <template #title>
                  <a-avatar :size="24" shape="square">
                    <img alt="avatar" :src="currentAvatar" />
                  </a-avatar>
                  通过群加好友【BUG】
                </template>
                <GroupAdd :currentWxid="currentWxid" v-if="loadedTabs['5']" />
              </a-tab-pane> -->
            </a-tabs>
          </a-card>
        </a-col>
      </a-row>
    </a-space>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useWeixinStore } from '@/store';
import { Message } from '@arco-design/web-vue';
import {
  updateFriendList,
  updateGroupList,
  editWeixn,
  getWxInfo,
} from '@/api/weixin';
import FriendList from './components/friend-list.vue';
import GroupList from './components/group-list.vue';
import FriendAdd from './components/friend-add.vue';
import GroupAdd from './components/group-add.vue';

const weixinStore = useWeixinStore();
const currentWxid = ref('');
const currentAvatar = ref('');
const position = ref('1');
const loading = ref(false);
const isautoPass = ref(false);

// 记录已加载的 tab
const loadedTabs = ref<{
  [key: string]: boolean;
}>({
  '1': false,
  '2': false,
  '3': false,
  '4': false,
});

// 当前激活的 tab
const activeTab = ref('1');

// 用于刷新子组件
const friendListRef = ref();
const groupListRef = ref();

// 添加获取微信信息的函数
const getWeixinInfo = async (wxid: string) => {
  try {
    const res: any = await getWxInfo(wxid);
    if (res.code === 20000) {
      // 更新自动通过好友开关状态
      isautoPass.value = res.data.isautoPass || false;
    } else {
      Message.error(res.msg || '获取微信信息失败');
    }
  } catch (error) {
    Message.error('获取微信信息失败');
  }
};

onMounted(async () => {
  await weixinStore.fetchWxList();
  // 如果有微信列表数据，默认选中第一个
  if (weixinStore.wxList.length > 0) {
    const defaultWxid = weixinStore.wxList[0].wxid;
    currentWxid.value = defaultWxid;
    currentAvatar.value = weixinStore.wxList[0].avatarUrl;
    await getWeixinInfo(defaultWxid);
    // 默认加载第一个 tab 的内容
    loadedTabs.value['1'] = true;
  }
});

const handleAutoAcceptChange = async (value: boolean) => {
  if (!currentWxid.value) {
    Message.warning('请先选择微信账号');
    isautoPass.value = !value;
    return;
  }

  try {
    const res: any = await editWeixn({
      mywxid: currentWxid.value,
      field: {
        isautoPass: value,
      },
    });

    if (res.code === 20000) {
      Message.success('设置已更新');
      isautoPass.value = value;
    } else {
      Message.error(res.msg || '设置更新失败');
      isautoPass.value = !value;
    }
  } catch (error) {
    Message.error('设置更新失败');
    isautoPass.value = !value;
  }
};

// 事件处理
const handle = async (record: any) => {
  currentWxid.value = record.wxid;
  currentAvatar.value = record.avatarUrl;
  await getWeixinInfo(record.wxid);
};

// 更新数据方法
const handleUpdateFriend = async () => {
  if (!currentWxid.value) return;
  loading.value = true;
  const res = await updateFriendList(currentWxid.value);
  if (res?.data?.code === 20000) {
    // 刷新好友列表
    friendListRef.value?.refresh?.();
  }
  loading.value = false;
};
const handleUpdateGroup = async () => {
  if (!currentWxid.value) return;
  loading.value = true;
  const res = await updateGroupList(currentWxid.value);
  if (res?.data?.code === 20000) {
    groupListRef.value?.refresh?.();
  }
  loading.value = false;
};

// 监听 tab 点击事件，按需加载对应组件
const handleTabClick = (key: string) => {
  loadedTabs.value[key] = true;
};
</script>

<style scoped>
.container {
  padding: 16px;
}
</style>